# coding=utf-8
import os
import configparser
import requests
import time
import hashlib
import json

apiUrl = "https://api.niutrans.com/v2/text/translate"

from_language = "zh"
to_language = "ja"
# Set your own appid/appkey.
def load_key():
    config_path = os.path.expanduser("~/.ssh/xiaoniu.ini")
    config = configparser.ConfigParser()
    config.read(config_path)
    appid = config.get("fanyi", "appid")
    secret = config.get("fanyi", "key")
    return appid, secret

app_id,apikey=load_key()
src_text = "待翻译文本，例如：欢迎使用我们的翻译系统。"

# 生成权限字符串
def generate_auth_str(params):
    sorted_params = sorted(list(params.items()) + [('apikey', apikey)], key=lambda x: x[0])
    param_str = '&'.join([f'{key}={value}' for key, value in sorted_params])
    md5 = hashlib.md5()
    md5.update(param_str.encode('utf-8'))
    auth_str = md5.hexdigest()
    return auth_str

# 获取翻译结果
def translate():
    data = {
        'from': from_language,
        'to': to_language,
        'appId': app_id,
        'timestamp': int(time.time()),
        'srcText': src_text
    }

    auth_str = generate_auth_str(data)
    data['authStr'] = auth_str
    print('Request=',data)
    response = requests.post(transUrl, data=data)
    print("翻译结果："+str(response.json()))
    return response.json()

if __name__ == "__main__":
    response_data = translate()